# Import the Response object from Flask to create HTTP responses.
from flask import Response
# Import components from the prometheus_client library for exposing metrics.
from prometheus_client import CONTENT_TYPE_LATEST, CollectorRegistry, generate_latest, multiprocess

# Import the main Flask application instance from the myapp package.
from myapp.app import app

# Get the application's configuration object.
config = app.config


# Define a route for a health check endpoint.
@app.route('/health')
def health():
    # This endpoint is typically used by load balancers or container orchestrators
    # to check if the application is running.
    return 'OK'


# Define another route for a health check endpoint.
@app.route('/healthcheck')
def healthcheck():
    # This provides an alternative name for the health check, often used for compatibility.
    return 'OK'


# Define a simple "ping" endpoint to check for basic responsiveness.
@app.route('/ping')
def ping():
    # This can be used for simple service availability checks.
    return 'OK'


# Define a route to expose application metrics for Prometheus.
@app.route('/metrics')
def metrics():
    # Create a new CollectorRegistry. A registry is used to collect all the metrics.
    registry = CollectorRegistry()
    # Use the MultiProcessCollector to aggregate metrics from multiple worker processes
    # (e.g., when running with Gunicorn).
    multiprocess.MultiProcessCollector(registry)
    # Generate the latest metrics in the Prometheus text format.
    data = generate_latest(registry)
    # Return the metrics data with the appropriate content type for Prometheus to scrape.
    return Response(data, mimetype=CONTENT_TYPE_LATEST)
